﻿using AutoMapper;
using Mysoft.Common.Extensions;
using Mysoft.Data;
using Mysoft.Domain.Basic;
using Mysoft.Dto;
using Mysoft.Dto.Basic;
using Mysoft.Entity;
using System.Linq.Expressions;
using System.Transactions;

namespace Mysoft.Domain
{
    public class TestDomainService:DomainBase
    {
        private readonly EntityService<Test> _entityService;
        private readonly IMapper _mapper;

        /// <summary>
        /// 依赖注入
        /// </summary>
        /// <param name="entityService"></param>
        /// <param name="mapper"></param>
        public TestDomainService(EntityService<Test> entityService, IMapper mapper)
        {
            _entityService = entityService;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public async Task<PageRespone<TestDto>> GetPageData(TestCondition condition) 
        {
            //动态表达式拼接
            Expression<Func<Test, bool>> where = LambdaExtensions.True<Test>();
            if (!string.IsNullOrWhiteSpace(condition.search)) where = where.And(m => m.Name.Contains(condition.search));
            var list = _entityService.Instance.IQueryablePage(where, condition.pageIndex, condition.pageSize, out int count,condition.orderBy).ToList();
            var dtos = _mapper.Map<List<TestDto>>(list);
            return new PageRespone<TestDto>(dtos, count);
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Guid> Add(TestDto dto) 
        {
            var test = _mapper.Map<Test>(dto);
            var info = await _entityService.Instance.AddAsync(test);
            return info.Id;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public void Delete(Guid? id)
        {
             _entityService.Instance.Delete(m => m.Id == id);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task Modify(TestDto dto)
        {
            var info = _entityService.Instance.FindFirst(dto.Id.Value);
            if (info == null)
            {
                return;
            }
            info.Name = dto.Name;
            info.Description = dto.Description;

            var result = _entityService.Instance.BeginTransaction(() =>
            {
                _entityService.Instance.Modify(info);
                return new Common.Response.ResponseContent();
            }, System.Data.IsolationLevel.ReadUncommitted);
         
        }

      
    }                                                 
}
